(function() {
    'use strict';

    /**
     * @ngdoc function
     * @name webApp.controller:DazheCtrl
     * @description
     * # DazheCtrl
     * Controller of the webApp
     */
    angular.module('webApp')
        .controller('DazheCtrl', DazheCtrl);

    DazheCtrl.$inject = ['$scope', 'dataService', 'helper', '$rootScope', '$location'];

    function DazheCtrl($scope, dataService, helper, $rootScope, $location) {

        //打折活动列表
        $scope.listAction = function() {
            $scope.pageSize = 10;
            $scope.getList(1);

            $scope.$on('event:up-store-id', function() {
                $scope.store_id = $rootScope.store_id
                $scope.getList(1);
            });
        }

        $scope.getList = function(pageNo) {
            var query = {
                page_no: pageNo ? pageNo : "1",
                page_size: $scope.pageSize
            };
            query.query = {
                "store_id": $scope.store_id
            };

            dataService.dazheGet(query).then(function(list) {
                if (list) {
                    for (var i in list.activitys) {
                        list.activitys[i].diff_time = $scope.diff_time(list.activitys[i].start_time, list.activitys[i].end_time)
                    }
                    $scope.dazhe_list = list.activitys;
                    $scope.dazhe_total = list.total_count;
                }
            });
        }

        //js计算两个时间的时间差
        $scope.diff_time = function(start_time, end_time) {
            var s_time = new Date().getTime();
            var start = new Date(start_time).getTime();
            var end = new Date(end_time).getTime();

            //判断当前时间是否大于结束时间
            if (s_time > end) {
                return 0;
            }

            //判断当前时间是否大于开始时间
            if (s_time > start && s_time < end) {
                var time = new Date().getTime();
            } else {
                var time = new Date(start_time).getTime();
            }

            //var diff = end_time * 1000 - start_time * 1000 //时间差的毫秒数  
            var diff = end - time;

            //计算出相差天数  
            var days = Math.floor(diff / (24 * 3600 * 1000));

            //计算出小时数  
            var leave1 = diff % (24 * 3600 * 1000); //计算天数后剩余的毫秒数  
            var hours = Math.floor(leave1 / (3600 * 1000));
            //计算相差分钟数  
            var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数  
            var minutes = Math.floor(leave2 / (60 * 1000));

            //计算相差秒数  
            var leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数  
            var seconds = Math.round(leave3 / 1000);

            var returnStr = seconds + "秒";
            if (minutes > 0) {
                returnStr = minutes + "分" + returnStr;
            }
            if (hours > 0) {
                returnStr = hours + "小时" + returnStr;
            }
            if (days > 0) {
                returnStr = days + "天" + returnStr;
            }
            return returnStr;
        }

        //打折添加页面
        $scope.addAction = function() {
            var activity_id = $location.search().activity_id;

            if (activity_id) {
                var query = {
                    "query": {
                        "activity_id": activity_id
                    }
                };

                dataService.dazheGet(query).then(function(result) {
                    if (result.total_count) {
                        $scope.dazhe_data = result.activitys[0];
                        if (!$scope.dazhe_data.store_id) {
                            $scope.dazhe_data.store_id = $rootScope.store_id;
                        }

                        $scope.dazhe_activity_id = activity_id;
                    }
                });
            } else {
                var data = {
                    "partner_id": dataService.currentLoginedUser().partner_id,
                    "store_id": $rootScope.store_id,
                    "name": "限时促销",
                    "ptype": 1,
                    "start_time": $scope.getDateStr(0),
                    "end_time": $scope.getDateStr(30),
                    "type_id": 1,
                    "discount": 90
                };
            }
            $scope.dazhe_data = data;
        }

        //打折活动添加
        $scope.dazheAdd = function(param) {
            if ($scope.dazhe_data.name.length > 5) {
                helper.myAlert("error:促销标题不能超过5个字");
                return false;
            }

            if (param != 'part') {
                if ($scope.dazhe_data.discount <= 0) {
                    helper.myAlert("error:折扣不能是0折");
                    return false;
                }

                if ($scope.dazhe_data.discount > 100) {
                    helper.myAlert("error:折扣不能超过100折");
                    return false;
                }
            }

            var activity_id = $location.search().activity_id;
            if (activity_id) {
                dataService.dazheUpdate($scope.dazhe_data).then(function(result) {
                    if (result.activity_id) {
                        // $scope.dazhe_activity_id = result.activity_id;
                        if (param) {
                            $scope.broadcast();
                            $scope.checkedBroadcast();

                            //部分商品编辑需要重新计算打折价格
                            // var query = {
                            //     "content": { "store_id": $rootScope.store_id, "dazhe_type": "all" }
                            // };
                            // $scope.nsqrequest(query);
                        }
                        //如果是全店商品打折的话，那么保存成功之后，直接跳转到首页 ptype = 1
                        if ($scope.dazhe_data.ptype == 1) {
                            // var query = {
                            //     "content": { "store_id": $rootScope.store_id, "dazhe_type": "all" }
                            // };
                            // $scope.nsqrequest(query);
                            helper.myAlert("success", "#/dazhe/list");
                        }

                        //把时间更改成过期时间，折后价需要清零
                        if ($scope.dazhe_data.end_time < $scope.getDateStr(0)) {
                            // var query = {
                            //     "content": { "store_id": $rootScope.store_id, "dazhe_type": "all", "delete": 1 }
                            // };
                            // $scope.nsqrequest(query);
                        }
                    }
                });
            } else {
                if ($scope.dazhe_activity_id) {
                    $scope.dazhe_data.activity_id = $scope.dazhe_activity_id;

                    dataService.dazheUpdate($scope.dazhe_data).then(function(result) {
                        if (result.activity_id) {
                            // $scope.dazhe_activity_id = result.activity_id;
                            if (param) {
                                // $scope.broadcast();
                                $scope.checkedBroadcast();
                            }

                            //如果是全店商品打折的话，那么保存成功之后，直接跳转到首页 ptype = 1
                            if ($scope.dazhe_data.ptype == 1) {
                                helper.myAlert("success", "#/dazhe/list");
                            }
                        }
                    });
                } else {
                    //全店活动只能创建一次
                    var quandian = {};
                    quandian.query = {
                        "store_id": $rootScope.store_id,
                        "ptype": 1
                    };

                    if ($scope.dazhe_data.ptype == 1) {
                        dataService.dazheGet(quandian).then(function(result) {
                            if (result.total_count && result.activitys[0]) {
                                helper.myAlert("error:全店打折只能创建一次");
                                return false;
                            } else {
                                $scope.oneAdd();
                            }
                        });
                    } else {
                        $scope.oneAdd(param);
                    }
                }
            }
        }

        $scope.oneAdd = function(param) {
            //校验store_id是否为0
            if (!$scope.dazhe_data.store_id) {
                helper.myAlert("store_id 错误不能保存，请联系客服！", "#/dazhe/list");
                return false;
            }
            dataService.dazheAdd($scope.dazhe_data).then(function(result) {
                if (result.activity_id) {
                    $scope.dazhe_activity_id = result.activity_id;
                    if (param) {
                        $scope.broadcast();
                        $scope.checkedBroadcast();
                    }
                    //如果是全店商品打折的话，那么保存成功之后，直接跳转到首页 ptype = 1
                    if ($scope.dazhe_data.ptype == 1) {
                        // var query = {
                        //     "content": { "store_id": $rootScope.store_id, "dazhe_type": "all" }
                        // };
                        // $scope.nsqrequest(query);

                        helper.myAlert("success", "#/dazhe/list");
                    }
                }
            });
        }

        //清空会员等级
        $scope.clearLevel = function() {
            $scope.dazhe_data.level = 0;
        }

        //$broadcast 两个参数，1、事件名称 2、传递参数 商品列表
        $scope.broadcast = function() {
            $rootScope.$broadcast("event:item-list", {
                activity_id: $scope.dazhe_activity_id
            });
        }

        //选中商品列表
        $scope.checkedBroadcast = function() {
            $rootScope.$broadcast("event:checked-item-list", {
                activity_id: $scope.dazhe_activity_id
            });
        }

        //nsq
        $scope.nsqrequest = function(data) {
            dataService.nsqRequest(data).then(function(result) {
                // console.error("result-->", result);
            });
        }

        //打折活动删除
        $scope.dazheDelete = function(activity_id) {
            helper.myConfirm('confirm operation', function() {
                var data = {
                    'activity_id': activity_id
                };

                dataService.dazheDelete(data).then(function(result) {
                    if (result.activity_id) {
                        $scope.getList(1);
                    } else {
                        helper.myAlert("error:" + result);
                    }
                });
            });
        }

        //tab切换
        $scope.tabCut = function($event) {
            $event.preventDefault();
            $($event.currentTarget).tab('show');
        }

        //切换折扣方式
        $scope.changeType = function(flag) {
            $scope.dazhe_data.type_id = flag;
        }

        //活动时间计算
        $scope.getDateStr = function(addDayCount) {
            var dd = new Date();
            dd.setDate(dd.getDate() + addDayCount);
            var y = dd.getFullYear();
            var m = (dd.getMonth() + 1) < 10 ? "0" + (dd.getMonth() + 1) : (dd.getMonth() + 1);
            var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
            var h = dd.getHours();
            var i = dd.getMinutes();
            if (i < 10) {
                i = "0" + i;
            }
            var s = dd.getSeconds();
            if (s < 10) {
                s = "0" + s;
            }

            return y + "-" + m + "-" + d + " " + h + ":" + i + ":" + s;
        }
    }
})();